package cn.cnlee.app.ui.home;

import android.os.Bundle;

import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

import cn.cnlee.app.base.BaseViewPagerFragment;
import cn.cnlee.app.config.Constants;
import cn.cnlee.app.pojo.IdTxtDTO;
import cn.cnlee.app.pojo.IndexDTO;
import cn.cnlee.app.repository.HomeRepository;
import cn.cnlee.app.vm.HomeViewModel;
import cn.cnlee.arch.base.BaseFragment;
import cn.cnlee.arch.util.Logger;

public class HomeFragment extends BaseViewPagerFragment<HomeViewModel> {

    private List<IdTxtDTO> navigationData = new ArrayList<>();

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void initView(Bundle state) {
        super.initView(state);
        setTitle("首页");
    }

    @Override
    protected void dataObserver() {
        registerSubscriber(HomeRepository.EVENT_KEY_NAVIGATION_DATA, IndexDTO.class).observe(this, indexDTO -> {
            if (indexDTO != null) {
                setData(indexDTO);
            }
        });
    }

    @Override
    protected void lazyLoad() {
        getNavigationData();
    }

    private void setData(IndexDTO indexDTO) {
//        List<IdTxtDTO> da = indexDTO.navigation.subList(2, 8);
//        mArrTitles = new String[da.size()];
//        navigationData.clear();
//        navigationData.addAll(da);
//        for (int j = 0; j < da.size(); j++) {
//            mArrTitles[j] = (da.get(j).text);
//        }
        mArrTitles = new String[indexDTO.navigation.size()];
        navigationData.clear();
        navigationData.addAll(indexDTO.navigation);
        for (int j = 0; j < indexDTO.navigation.size(); j++) {
            mArrTitles[j] = (indexDTO.navigation.get(j).text);
        }
        initFragment();
        setAdapter();
    }

    private void initFragment() {
        for (int i = 0; i < navigationData.size(); i++) {
            ModuleFragment moduleFragment = ModuleFragment.newInstance();
            Bundle bundle = new Bundle();
            bundle.putInt(Constants.F_PID, navigationData.get(i).id);
            moduleFragment.setArguments(bundle);
            mFragments.add(moduleFragment);
        }
    }

    @Override
    protected void onStateRefresh() {
        super.onStateRefresh();
        getNavigationData();
    }

    @Override
    protected String[] createPageTitle() {
        return mArrTitles;
    }

    @Override
    protected List<BaseFragment> createFragments() {
        return mFragments;
    }

    private void getNavigationData() {
        mViewModel.getHomeData();
    }

    @Override
    protected void setTitle(String titleName) {
        //去掉标题
    }
}
